import { Component, OnInit } from '@angular/core';
import { BladeContainerBase } from "../../../../shared/blade/blade-container-base";
import { StationTag } from "../../../../entity/station-tag.model";
import { StationTagService } from "../../../../service/station-tag.service";
import { FormBuilder, Validators, FormControl } from "@angular/forms";
import { Command } from "../../../../shared/toolbar.service";
import { Observable } from "rxjs/Observable";
import { MyValidators } from "../../../../utils/validator/rang";
import { Farm } from "../../../../entity/farm.model";

@Component({
	selector: 'app-station-tag-edit',
	templateUrl: './station-tag-edit.component.html',
	styleUrls: ['./station-tag-edit.component.css']
})
export class StationTagEditComponent extends BladeContainerBase<StationTag> {

	constructor(
		private fb: FormBuilder,
		private stationTagService: StationTagService,
	) {
		super(fb);
	}

	ngOnInit() {
		//编辑时注册按钮和按钮命令    
		if (!this.isNew) {
			this.commands = [
				new Command("save", "保存", "fa fa-save", "setofkey:update", (blade) => this.exeSaveChange(blade), (blade) => this.canSaveChange(blade)),
				new Command("reset", "重置", "fa fa-save", "setofkey:reset", (blade) => this.exeReset(blade), (blade) => this.canReset(blade)),
			]
		}
		else {
			this.currentEntity = new StationTag(0, (this.parentBlade.parentEntity as Farm).farmId, "", "");	
		}
		super.ngOnInit();
	}

	/**
     * 初始化数据
     * 
     * 
     * @memberof StationTagEditComponent
     */
	initData(): any | Observable<any> | Promise<any> {
		this.formPatchValue(this.currentEntity);
	}
	exeSaveChange(blade: any): void {
		this.saveChange();
	}
	canSaveChange(blade: any): boolean {
		return this.hasChange() && !this.hasError();
	}
	exeReset(blade: any): void {
		return this.formGroup.reset(this.currentEntity);
	}
	canReset(blade: any): boolean {
		return this.hasChange();
	}

	/**
    * 创建表单
    * 
    * 
    * @memberof DicKeyEditComponent
    */
	createForm() {
		this.formGroup = this.fromBuider.group({
			"farmId":[this.currentEntity.farmId],
			"stationTagName": [this.currentEntity.stationTagName, [
				Validators.required,
				// Validators.pattern("^[\u4e00-\u9fa5a-zA-Z0-9]+$"),
				Validators.maxLength(100),
			], //(control: FormControl): any => this.stationNameAsnyValidator(control, "stationTagName", this.currentEntity.stationTagName)
			],
			"stationTagCode": [this.currentEntity.stationTagCode, [
				Validators.required,
				Validators.pattern("[0-9a-zA-Z_.]{1,20}"),
				Validators.maxLength(40)
			], //(control: FormControl): any => this.stationCodeAsnyValidator(control, "stationTagCode", this.currentEntity.stationTagCode)
			],
			"expressionMark": [this.currentEntity.expressionMark, [
				//Validators.pattern("[0-9a-zA-Z_.]{1,20}"),		
				Validators.maxLength(45)
			]
			],
			"coefficient": [this.currentEntity.coefficient, [
				//MyValidators.rang(0, 255)			
				Validators.pattern("[0-9]{1,5}(\\.{0,1}[0-9]{1,2})?"),
			]
			],
			"stationTagSeq": [this.currentEntity.stationTagSeq, [
				MyValidators.rang(0, 255)
			]
			],
		});
	}

	/**
    * 设置表单错误对象
    * 
    * 
    * @memberof BladeContainerBase
    */
	setFormError(): void {
		this.formErrors = {
			'stationTagName': '',
			'stationTagCode': '',
			'expressionMark': '',
			'coefficient': '',
			'stationTagSeq': '',
		};
	}
    /**
    * 设置表单验证信息
    * 
    * 
    * @memberof BladeContainerBase
    */
	setValidationMessages(): void {
		this.validationMessages = {
			'stationTagName': {
				'required': '关口表名称不能为空。',
				'pattern': '关口表名称必须是汉字字母数字。',
				'maxlength': '关口表名称不能多于100个字符长度。',
				'exist': '关口表名称已存在。',
			},
			'stationTagCode': {
				'required': '关口表代码不能为空。',
				'pattern': '关口表代码由英文、数字组成。',
				'maxlength': '关口表代码不能多于40个字符长度。',
				'exist': '关口表代码已存在。',
			},
			'expressionMark': {
				'maxlength': '表达式标识不能多于45个字符长度。',
			},
			'coefficient': {
				'pattern': '长度不超过7位并且小数点后最多两位。',				
			},
			'stationTagSeq': {
				'rang': '排序值范围是0~255。',
			}
		};
	}

	/**
     * 异步校验stationName是否存在
     * 
     * @param {FormControl} control 
     * @returns {Promise<true>} 
     * 
     * @memberof StationTagEditComponent
     */
	stationNameAsnyValidator(control: FormControl, name: string, current: any): any {   //第三个参数为farmId
		if (!control.value || control.value == current) {
			return Observable.of(null);
		}
		return this.stationTagService.hasStationTagName(control.value, this.currentEntity.stationTagId, this.currentEntity.farmId)
			.map(res => res ? { exist: true } : null);
	}

	/**
     * 异步校验stationCode是否存在
     * 
     * @param {FormControl} control 
     * @returns {Promise<true>} 
     * 
     * @memberof StationTagEditComponent
     */
	stationCodeAsnyValidator(control: FormControl, name: string, current: any): any {
		if (!control.value || control.value == current) {
			return Observable.of(null);
		}
		return this.stationTagService.hasStationTagCode(control.value, this.currentEntity.stationTagId, this.currentEntity.farmId)
			.map(res => res ? { exist: true } : null);
	}

	/**
     * 创建一个关口表
     * 
     * 
     * @memberof TurbstatusEditComponent
     */
    onCreate() {
        if (!this.hasError()) {
			this.changeCurrent();
            this.stationTagService.create(this.currentEntity)
                .then(res => {
                    if (res) {
                        let parentContainerInstance = this.parentBlade.bladeContainerInstance;
                        parentContainerInstance.refresh(res);
                        this.bladeService.closeBlade(this.currentBlade);
                    }
                })
                .catch(error => this.bladeData.error = error)
                .then(res => this.bladeData.isLoading = false);
        }
	}
	
    /**
     * 保存编辑
     * 
     * @memberof TurbstatusEditComponent
     */
    saveChange(): any | Promise<any> | Observable<any> {

        if (this.canSaveChange(this.currentBlade)) {
            this.changeCurrent();
            return this.stationTagService.update(this.currentEntity)
                .then(res => {
                    if (res) {
                        (this.parentBlade.bladeContainerInstance).refresh(res);
                        this.bladeService.closeBlade(this.currentBlade);
                        return true;
                    }
                })
                .catch(error => this.bladeData.error = error)
                .then(res => this.bladeData.isLoading = false);
        }
    }
    changeCurrent() {
        this.bladeData.isLoading = true;
        let formValue = this.formGroup.value as StationTag;
        this.currentEntity.stationTagName = formValue.stationTagName;
        this.currentEntity.stationTagCode = formValue.stationTagCode;
        this.currentEntity.expressionMark = formValue.expressionMark;
        this.currentEntity.coefficient = formValue.coefficient;
        this.currentEntity.stationTagSeq = formValue.stationTagSeq;
        this.currentEntity.farmId = formValue.farmId;
    }

}



// WEBPACK FOOTER //
// ./src/app/module/basic/station-tag/station-tag-edit/station-tag-edit.component.ts